﻿using System;
using System.Data;
using System.IO;
using Epi;
using Epi.Data;

namespace Menafrinet.ViewModel
{
    public abstract class DataHelperBase : ObservableObject, IDataHelper
    {
        public View CaseForm { get; set; }
        public Project Project { get; set; }
        public IDbDriver Database { get; protected set; }

        public abstract void RepopulateCollections();
        protected virtual void ClearCollections() { }
        protected virtual DataTable GetCasesTable() 
        {
            Query selectQuery = Database.CreateQuery("SELECT * " + CaseForm.FromViewSQL);// + " WHERE [RECSTATUS] > 0");
            return Database.Select(selectQuery);
        }

        protected bool LoadConfig()
        {
            string configFilePath = Configuration.DefaultConfigurationPath;
            bool configurationOk = true;
            try
            {
                string directoryName = System.IO.Path.GetDirectoryName(configFilePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (!File.Exists(configFilePath))
                {
                    Configuration defaultConfig = Configuration.CreateDefaultConfiguration();
                    Configuration.Save(defaultConfig);
                }

                Configuration.Load(configFilePath);
            }
            catch (Epi.ConfigurationException ex)
            {
            }
            catch (Exception ex)
            {
                configurationOk = ex.Message == "";
            }
            return configurationOk;
        }
    }
}
